//
//  RJCheckReasonVC.m
//  AirQuality
//
//  Created by Po on 15/4/7.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCheckReasonVC.h"

static NSInteger  markCount;
@interface RJCheckReasonVC () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (weak, nonatomic) IBOutlet UILabel *headLabel;
@property (weak, nonatomic) IBOutlet UITextField *valueTextFiled;
@property (weak, nonatomic) IBOutlet UIButton *validButton;
@property (weak, nonatomic) IBOutlet UIButton *unValidButton;
@property (weak, nonatomic) IBOutlet UITextField *validReasonTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *unValidTextFiled;
@property (weak, nonatomic) IBOutlet UIButton *customButton;
@property (weak, nonatomic) IBOutlet UIImageView *corView;

@property (retain, nonatomic) UIButton * currentButton;
@property (retain, nonatomic) UITextField * currentTextField;
@property(assign) BOOL mark;
@property(assign) BOOL isQuality;
@property (strong, nonatomic) NSString * checkValue;
@property (assign) BOOL canSure;

- (void)initInterface;
@end

@implementation RJCheckReasonVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setFrame:ScreenBounds];
    [self initInterface];
    _mark = NO;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    _isQuality = NO;
     NSString * string = [NSString stringWithFormat:@"%ld",markCount-1];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sendCheckProplemData" object:string];
}
- (void)initInterface
{   [_valueTextFiled setDelegate:self];
    [_validReasonTextFiled setDelegate:self];
    [_unValidTextFiled setDelegate:self];
    NSString * timepoint = _checkData[@"timepoint"];
    NSString *timeString = [timepoint substringWithRange:NSMakeRange(11, 5)];
    NSMutableString * headText = [[NSMutableString alloc] initWithString:timeString];
    [headText appendFormat:@" 【 %@ : %@ 】",_checkData[@"GasType"],_checkData[@"value"]];
    [_headLabel setText:headText];
    _checkValue = _checkData[@"value"];
    _valueTextFiled.text = _checkValue;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShow:)
                                                 name:UIKeyboardDidShowNotification object:nil];

  
    _corView.image = [UIImage imageNamed:@"radioButtonNormal"];
 
    [_customButton addTarget:self action:@selector(pressQualityControl:) forControlEvents:UIControlEventTouchUpInside];
    _customButton.userInteractionEnabled = NO;
    
    
}

- (void)pressQualityControl:(UIButton *)sender{
    _isQuality = !_isQuality;
    _corView.image = _isQuality ? [UIImage imageNamed:@"radioButtonSelect"] :[UIImage imageNamed:@"radioButtonNormal"];
}
#pragma mark - function
- (NSString *)getNewMark
{
    NSString * buttonTitle = _currentButton.titleLabel.text;
    if ([buttonTitle isEqualToString:@" 质量控制"]) {
        return @"ZK,RM";
    } else if ([buttonTitle isEqualToString:@" 零点校准"]) {
        return @"CZ,RM";
    } else if ([buttonTitle isEqualToString:@" 跨度校准"]) {
        return @"CS,RM";
    } else if ([buttonTitle isEqualToString:@" 浮尘天气"]) {
        return @"FC,RM";
    } else if ([buttonTitle isEqualToString:@" 秸秆燃烧"]) {
        return @"JG,RM";
    } else if ([buttonTitle isEqualToString:@" 重污染天气"]) {
        return @"ZWR,RM";
    } else if ([buttonTitle isEqualToString:@" 自定义无效说明"]) {
        if (_isQuality) {
            return [NSString stringWithFormat:@"%@%@,RM",@"【质控数据】",_unValidTextFiled.text];
        }else
            return [NSString stringWithFormat:@"%@,RM",_unValidTextFiled.text];
       
    } else {
        if (_isQuality) {
          return [NSString stringWithFormat:@"%@%@",@"【质控数据】",_validReasonTextFiled.text];
        }else
           return [NSString stringWithFormat:@"%@",_validReasonTextFiled.text];
    }
    return nil;
}

#pragma mark - event
- (IBAction)pressReasonButton:(UIButton *)sender {
    [self.view endEditing:YES];
    _mark = YES;
    if (sender.tag == 1000 || sender.tag == 1001) {
        _customButton.userInteractionEnabled = YES;
    }else{
       _customButton.userInteractionEnabled = NO;
    }
    _isQuality = NO;
    _corView.image = [UIImage imageNamed:@"radioButtonNormal"];
    if (_currentButton == sender) {
        return;
    }
    
    if (!_currentButton) {
        _currentButton = sender;
        [_currentButton setSelected:YES];
        return;
    }
    
    [_currentButton setSelected:NO];
    //清空输入框
    NSString * buttonTitle = _currentButton.titleLabel.text;
    if (![buttonTitle isEqualToString:@"自定义无效说明"]) {
        [_unValidTextFiled setText:@""];
    }
    if (![buttonTitle isEqualToString:@"自定义有效说明"]){
        [_validReasonTextFiled setText:@""];
    }
    
    _currentButton = sender;
    [_currentButton setSelected:YES];
}

- (IBAction)pressCancelButton:(UIButton *)sender {
    [self removeSelf];
}

- (IBAction)pressComfirmButton:(UIButton *)sender {
    
    //获取请求Json字符串
    NSString * newMark = [self getNewMark];
    //自定义是否有效
    if (![_validReasonTextFiled.text isEqualToString:@""] || ![_unValidTextFiled.text isEqualToString:@""]) {
        _mark = YES;
        _canSure = YES;
    }
    if (![_checkValue isEqualToString:_valueTextFiled.text]) {
        if (!_canSure) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择或填写说明" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
    }
    if ([_checkValue isEqualToString:_valueTextFiled.text]) {
        if (!_canSure) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您没有做任何操作" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [alert show];
            return;
        }
    }
    
    NSArray * data = @[@{@"stationcode" :_checkData[@"stationcode"],
                         @"timepoint"   :_checkData[@"timepoint"],
                         @"OldValue"    :_checkData[@"value"],
                         @"OldMark"     :_checkData[@"OldMark"],
                         @"NewValue"    :_valueTextFiled.text,
                         @"NewMark"     :newMark,
                         @"GasType"     :[_checkData[@"GasType"] uppercaseString],
                         @"IsValidation":@false}
                       ];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //发送修改请求 /smartadmin/audit/update
    //http://xsscd.xicp.net:5100/smartadmin/audit/update [NetURL defaultURL].Check
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].Check data:@{@"update":jsonString} completeBlock:^(id responseObject) {
        if (_delegate) {
            BOOL change;
            if (self.valueTextFiled.text.length == 0) {
                change = NO;
            }else{
                change = YES;
            }
            
            [_delegate checkReason:self value:@([_valueTextFiled.text floatValue]) newMark:newMark isChange:change];
        }
        if (_mark) {
            markCount --;
        }
    } failBlack:^(id response) {
        NSLog(@"--");
    }];
    //移除视图
    [self removeSelf];
}
- (IBAction)cancelCheck:(id)sender {
    _mark = NO;
}

- (void)removeSelf
{
    _mark = NO;
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint point = [[touches anyObject] locationInView:self.view];
    if ((point.y > CGRectGetMaxY(_mainView.frame)) || (point.y < _mainView.frame.origin.y)) {
        [self removeSelf];
    }
    
    [self.view endEditing:YES];
}

#pragma mark - UITextFiledDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (_currentTextField != textField) {
        _currentTextField = textField;
    }else{
        textField.text = @"";
    }
    if (textField == _validReasonTextFiled) {
        (_currentButton) ? [_currentButton setSelected:NO]:nil;
        _currentButton = _validButton;
        [_currentButton setSelected:YES];
    } else if (textField == _unValidTextFiled) {
        (_currentButton) ? [_currentButton setSelected:NO]:nil;
        _currentButton = _unValidButton;
        [_currentButton setSelected:YES];
    }

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (self.view.frame.origin.y != 0) {
        CGRect rect = self.view.frame;
        rect.origin.y = 0;
        [UIView animateWithDuration:0.2 animations:^{
            [self.view setFrame:rect];
        }];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger tag = textField.tag;
    if (tag != 10) {
        return YES;
    }
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)keyboardWasShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGFloat keyBoardHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;//得到键盘的高度
    CGFloat moveHeight = (CGRectGetMaxY(_currentTextField.frame) + keyBoardHeight + _mainView.frame.origin.y) - ScreenHeight;
    if (moveHeight > 0) {
        CGRect rect = self.view.frame;
        rect.origin.y -= moveHeight;
        [UIView animateWithDuration:0.3f animations:^{
            [self.view setFrame:rect];
        }];
    }
}
- (IBAction)propertyBtn:(UIButton *)sender {
    
    _canSure = YES;
}

@end
